package com.hqyj.shrio;


import com.hqyj.dao.UserMapper;
import com.hqyj.pojo.User;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.List;


@Component
public class MyRealm extends AuthorizingRealm {
    //注入dao
    @Autowired
    UserMapper mapper;
    //权限校验
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //1.获取用户名
        String userName = principalCollection.fromRealm(this.getName()).iterator().next()+"";
        //2 查询认证用户拥有的角色
        List<String> listRole = mapper.selectRoleByName(userName);
        for (String s : listRole) {
            System.err.println(userName+"拥有的角色是："+s);
        }
        //3 给用户分配角色
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addRoles(listRole);
        //分配权限的方法
        // info.addStringPermissions(listRole);
        return info;
    }
    //登录判断
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //获取令牌
        UsernamePasswordToken up =(UsernamePasswordToken) token;
        //取出用户名
        String userName = up.getPrincipal()+"";
        //验证用户名是否正确
        User a = new User();
        a.setUserName(userName);
        User user = mapper.login(a);
        if (user == null){
            throw new UnknownAccountException();
        }
        //密码校验

        return new SimpleAuthenticationInfo(user.getUserName(),user.getUserPassword(), new Md5Hash(userName), this.getName());
    }
}
